package com.epoch.platform.sys.menu.controller;

import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.epoch.base.annotation.ControllerBind;
import com.epoch.base.base.BaseController;
import com.epoch.base.function.BeetlFunctions;
import com.epoch.base.util.AjaxResult;
import com.epoch.base.util.JSONUtils;
import com.epoch.base.util.LoggerUtil;
import com.epoch.platform.sys.menu.dao.SysMenu;
import com.epoch.platform.sys.menu.service.SysMenuService;
import com.epoch.platform.sys.rolemenu.dao.SysRoleMenu;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.SqlPara;

@ControllerBind(controllerKey = "/sys/menu")
public class SysMenuController extends BaseController {

	private SysMenuService sysMenuService = new SysMenuService();

	private AjaxResult ajaxResult = new AjaxResult();

	/**
	 * 选项卡页面
	 */
	public void index() {
		render("/sys/menu/sys_menu_tab.html");
	}
	
	public void listUI() {
        setAttr("treeNodeJson", JSONUtils.toJSONString(sysMenuService.getAllTreeMenuList()));
        render("/sys/menu/sys_menu_list.html");
    }
	
	/**
     * 菜单列表页面
     */
    public void findMenuListAjax() {
        // 保存一个AjaxResult对象进入域中
        Kv param = Kv.create();
        SqlPara sqlPara = Db.getSqlPara("systemManage.findAllSysMenuList", param);
        List<SysMenu> sysMenuList= SysMenu.dao.find(sqlPara);
        renderJson(new Page<>(sysMenuList, 1, 1, 1, sysMenuList.size()));
    }
    
    public void suvUI() {
        String id = getPara("ID");
        String parentId = getPara("parentId");
        setAttr("parentId", parentId);
        String parentName = getPara("parentName");
        if(null == parentName) {
        	setAttr("parentName", "菜单树");
        }else {
        	setAttr("parentName", parentName);
        }
        SysMenu sysMenu;
        if (StringUtils.isNotBlank(id)) {
            sysMenu = SysMenu.dao.findById(id);
            SysRoleMenu roleMenu = SysRoleMenu.dao.findFirst(Db.getSql("systemManage.findSysMenu"), id);
            sysMenu.put("menuRole", roleMenu != null ? roleMenu.getStr("menuRole") : "");
            setAttr("menuRoleShow", roleMenu != null ? roleMenu.getStr("menuRoleShow") : "");
            setAttr("menuRoleShowByLine", roleMenu != null&&roleMenu.getStr("menuRoleShow")!=null ? roleMenu.getStr("menuRoleShow").replaceAll(",","\r\n") : "");
            //取出父节点ID，并且查询父节点信息
            SysMenu sysMenuParent = SysMenu.dao.findById(sysMenu.getStr("parent_id"));
            if (sysMenuParent != null) {
                setAttr("parentId", sysMenu.getStr("parent_id"));
                setAttr("parentName", sysMenuParent.getStr(SysMenu.MENU_NAME));
            }
        } else {
            sysMenu = new SysMenu();
        }
        setAttr("treeNodeJson", JSONUtils.toJSONString(sysMenuService.getAllTreeMenuList()));
        setAttr("sysMenu", sysMenu);
        render("/sys/menu/sys_menu_edit.html");
    }
    
    public void suv() {
    	try {
    		 SysMenu sysMenu = getModel(SysMenu.class, "sysMenu",true);
    		 if (sysMenu != null) {
                 if (sysMenu.saveOrUpdate()) {
                     String menuId = sysMenu.getStr("id").toString();
                     Db.update(Db.getSql("systemManage.deleteMenuRoleByMenuId"), menuId);
                     String roleIdStr = getPara("userRole", null);
                     if (StringUtils.isNotBlank(roleIdStr)) {
                         String[] roleIds = roleIdStr.split(",");
                         //4.保存菜单现有的角色
                         for (String roleId : roleIds) {
                             SysRoleMenu roleMenu = new SysRoleMenu();
                             roleMenu.set("MENU_ID", menuId);
                             roleMenu.set("ROLE_ID", roleId);
                             roleMenu.save();
                         }
                     }
                 }
             }
    		 renderJson(ajaxResult.success("保存成功"));
    	}catch (Exception e) {
			// TODO: handle exception
		}
    }
    
    /**
     * 删除
     */
    public void delete() {
        String[] ids = getParaValues("ids[]");
        try {
            if (ids != null && ids.length > 0) {
                for (String id : ids) {
                    SysMenu.dao.deleteById(id);
                }
            }
            BeetlFunctions.initMenuCode();
            ajaxResult.success("删除成功!");
        } catch (Exception e) {
            e.printStackTrace();
            LoggerUtil.getLogger().error(" ids:{},删除失败:{}", ids, e.getMessage());
            ajaxResult.addError("删除失败");
        }
        renderJson(ajaxResult);

    }

}
